package modele;
	
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import DB.Personne;

public class Acces {
	
	public static String SORTIE = "sortie";
	public static String ENTREE = "entree";
	
	private Personne personne;
	private Batiment batiment;
	private String date;
	private String type;
	
	public Acces (Personne personne, Batiment batiment, String type){
		this.setPersonne(personne);
		this.setBatiment(batiment);
		this.setDate(new Date());
		this.setType(type);
		this.save();
	}
	public Acces (Personne personne, Batiment batiment, String type,String date){
		this.setPersonne(personne);
		this.setBatiment(batiment);
		this.setDate(date);
		this.setType(type);
	}
	
	
	public Personne getPersonne() {
		return personne;
	}
	public void setPersonne(Personne personne) {
		this.personne = personne;
	}
	
	public Batiment getBatiment() {
		return batiment;
	}
	public void setBatiment(Batiment batiment) {
		this.batiment = batiment;
	}
	
	public String getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date.toString();
	}
	private void setDate(String date2) {
		this.date = date2;
	}
	public String toString()
	{
		return " "+this.getType()+this.getPersonne().getNom()+" "+this.getPersonne().getPrenom()+" "+this.getBatiment().getNom()+" "+this.getDate();
	}

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param type the type to set
	 */
	private void setType(String type) {
		this.type = type;
	}

	private void save()
	{
		Element racine = null;
			SAXBuilder sxb = new SAXBuilder();
			try {
				try {
					racine = sxb.build(new File(XMLParser.xmlPath)).getRootElement();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (JDOMException e) {
				e.printStackTrace();
			}
			Element acces = new Element("acces");
			Element id = new Element("id");
			id.setText(this.getPersonne().getID());
			Element batiment = new Element("batiment");
			batiment.setText(this.getBatiment().getID());
			Element type = new Element("type");
			type.setText(this.getType());
			Element date = new Element("date");
			date.setText(this.getDate());
			
			acces.addContent(id);
			acces.addContent(batiment);
			acces.addContent(type);
			acces.addContent(date);
			
			racine.getChild("journal").addContent(acces);
		try
		   {
		      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		      sortie.output(racine, new FileOutputStream(XMLParser.xmlPath));
		   }
		   catch (java.io.IOException e){}
	}
	
	
	public static void main(String[] args)
	{
		
		Acces acc = new Acces(new Personne("Laignel", "Cyril", "123456"), new Batiment("Maurienne", "Maurienne3"),Acces.ENTREE);
		System.out.println(acc.toString());
		
	}
}
